﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;

namespace Frogs.Stability.LeakyBucket
{
	/// <summary>
	/// Default implementation of Frogs.Stability.LeakyBucket.IBucketTimer
	/// </summary>
	public class DefaultBucketTimer : IBucketTimer
	{
		Timer _timer = new Timer();

		/// <summary>
		/// Instatiates a Frogs.Stability.LeakyBucket.DefaultBucketTimer
		/// </summary>
		public DefaultBucketTimer(int interval)
		{
			this.Interval = interval;

			this._timer.AutoReset = true;
			this._timer.Elapsed += (s, e) =>
				{
					this.OnBucketTimerElapsed();
				};
		}

		/// <summary>
		/// Start the timer
		/// </summary>
		public void Start()
		{
			if (!this._timer.Enabled)
			{
				this._timer.Enabled = true;
			}
		}

		/// <summary>
		/// Stop the timer
		/// </summary>
		public void Stop()
		{
			if (this._timer.Enabled)
			{
				this._timer.Enabled = false;
			}
		}

		/// <summary>
		/// Gets or sets the interval for the timer
		/// </summary>
		public double Interval
		{
			get
			{
				return this._timer.Interval;
			}
			set
			{
				this._timer.Interval = value;
			}
		}

		/// <summary>
		/// 
		/// </summary>
		public event BucketTimerElapsedEventHandler Elapsed;
		private void OnBucketTimerElapsed()
		{
			var tmp = this.Elapsed;
			if (tmp != null)
			{
				tmp(this, new EventArgs());
			}
		}
	}
}
